import "./index.scss";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import { useState, useEffect } from "react";
import {
  Tabs,
  Button,
  Select,
  Form,
  Input,
  Modal,
  Space,
  Table,
  message,
  Popconfirm,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { Link, useNavigate } from "react-router-dom";
import http from "../../../utils/http";
import { CSVLink } from "react-csv";

const PolicyArticles = () => {
  //时间转换
  const toDub = (n: any) => (n < 10 ? "0" + n : "" + n);
  //年月日时分秒
  const toTime = (date: any) => {
    const oTime = new Date(date);
    return (
      oTime.getFullYear() +
      "-" +
      toDub(oTime.getMonth() + 1) +
      "-" +
      toDub(oTime.getDate()) +
      " " +
      toDub(oTime.getHours()) +
      ":" +
      toDub(oTime.getMinutes()) +
      ":" +
      toDub(oTime.getSeconds())
    );
  };

  //标签页
  const onChange = (key: string) => {
    console.log(key);
  };

  //数据类型
  interface DataType {
    key: string;
    atitle: string;
    atype: string;
    atime: string;
    acontent: string;
  }

  // 渲染数据
  const getData = () => {
    http({
      url: "/getArticle",
    }).then((res) => {
      console.log("所有数据", res);

      let _data = res.data.map((v: { id: number }) => {
        return { ...v, key: v.id };
      });
      setData(_data);
    });
  };
  useEffect(() => {
    getData();
  }, []);

  // 搜索信息
  const onSearch = (search: any) => {
    console.log(search);

    http({
      url: "/searchArticle",
      params: {
        atitle: search.atitle || "",
        atype: search.atype || "",
      },
    }).then((res: { [key: string]: any }) => {
      console.log(res);
      if (res.error == 0) {
        message.success("查询成功");
        let _data = res.data.map((v: { id: number }) => {
          return { ...v, key: v.id };
        });
        setData(_data);
        // getData()
      } else {
        message.error("查询失败");
      }
    });
  };

  //清空搜索
  const [searchText] = Form.useForm();
  const clear = () => {
    searchText.resetFields();
    getData();
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  //点击名字跳转详情
  const navigate = useNavigate();
  const toDetail1 = (record: any) => {
    console.log("record", record);
    navigate(`/home/ArticleDetails`, { state: record });
  };

  //表格
  const columns: ColumnsType<DataType> = [
    {
      title: "标题",
      dataIndex: "atitle",
      key: "atitle",
      render: (text, record) => (
        <a
          onClick={() => {
            toDetail1(record);
          }}
          className="delete"
        >
          {text}
        </a>
      ),
    },
    {
      title: "分类",
      dataIndex: "atype",
      key: "atype",
    },
    {
      title: "提交时间",
      dataIndex: "atime",
      key: "atime",
      render: (text) => <a className="todate">{toTime(text)}</a>,
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: any) => (
        <Space size="middle">
          <a
            className="delete"
            onClick={() => {
              showEdit(record);
            }}
          >
            编辑
          </a>
          <Popconfirm
            title="你确定删除这条信息吗?"
            onConfirm={() => {
              confirm(record);
            }}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <a href="#" className="delete1">
              删除
            </a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const [data, setData] = useState([]);

  // 编辑框
  const [editForm] = Form.useForm();
  const [isModalOpen, setIsEditOpen] = useState(false);

  const showEdit = (record: any) => {
    console.log("editrecord", record);
    editForm.setFieldsValue({ ...record });
    setIsEditOpen(true);
  };

  // 确定编辑
  const handleOk = () => {
    const data = editForm.getFieldsValue(true);
    const aa = data.acontent.substring(3);
    const newTitle = aa.substring(0, aa.indexOf("<"));

    http({
      url: "/editArticle",
      method: "post",
      data: {
        id: data.id,
        atitle: data.atitle,
        atype: data.atype,
        acontent: newTitle,
      },
    }).then((res: { [key: string]: any }) => {
      console.log(res);
      if (res.error == 0) {
        message.success("修改成功");
        setIsEditOpen(false);
        getData();
      }
    });
    setIsEditOpen(false);
  };

  const handleCancel = () => {
    setIsEditOpen(false);
  };

  // 确定删除
  const confirm = (record: { id: number }) => {
    http({
      url: "/deleteArticle",
      method: "post",
      data: {
        id: record.id,
      },
    }).then((res: { [key: string]: any }) => {
      // console.log(res);
      if (res.error == 0) {
        message.success("删除成功");
        getData();
      }
    });
  };

  const cancel = () => {
    message.error("取消删除");
  };

  // 确定新增
  const [addText] = Form.useForm();
  const onAdd = (values: any) => {
    let nowTime = getNowDate();
    console.log("Add:", values);
    //截取富文本导出的字符串
    let aaa = values.acontent;
    let newAcon = aaa.substring(3);
    let newAcontent = newAcon.substring(0, newAcon.length - 4);
    http({
      url: "/addArticle",
      method: "post",
      data: {
        atype: values.atype,
        atitle: values.atitle,
        acontent: newAcontent,
        atime: nowTime,
      },
    }).then((res) => {
      console.log(res);
      message.success("添加成功");
      addText.resetFields();
      getData();
    });
  };

  //获取提交时的当前时间
  // 获得当前时间
  const getNowDate = () => {
    const myDate = new Date();
    const year = myDate.getFullYear(); // 获取当前年
    const mon = myDate.getMonth() + 1; // 获取当前月
    const date = myDate.getDate(); // 获取当前日
    const hours = myDate.getHours(); // 获取当前小时
    const minutes = myDate.getMinutes(); // 获取当前分钟
    const seconds = myDate.getSeconds(); // 获取当前秒
    const now =
      year +
      "-" +
      mon +
      "-" +
      date +
      " " +
      hours +
      ":" +
      minutes +
      ":" +
      seconds;
    //console.log(now);
    return now;
  };

  return (
    <div className="policyArticles">
      <div className="title">政策通告文章</div>
      <div className="hr"></div>

      <Tabs
        defaultActiveKey="1"
        onChange={onChange}
        items={[
          {
            label: `文章列表`,
            key: "1",
            children: (
              <>
                <Form
                  className="listBox"
                  name="customized_form_controls"
                  layout="inline"
                  initialValues={{ remember: true }}
                  form={searchText}
                  autoComplete="off"
                  onFinish={onSearch}
                  onFinishFailed={onFinishFailed}
                >
                  <Form.Item name="atitle" label="文章标题">
                    <Input />
                  </Form.Item>

                  <Form.Item label="分类" name="atype">
                    <Select style={{ width: "151px" }}>
                      <Select.Option value="公告类">公告类</Select.Option>
                      <Select.Option value="知识类">知识类</Select.Option>
                      <Select.Option value="新闻类">新闻类</Select.Option>
                    </Select>
                  </Form.Item>

                  <Form.Item>
                    <Button className="btn" htmlType="submit">
                      查询
                    </Button>
                  </Form.Item>

                  <Form.Item>
                    <Button className="btn" onClick={clear}>
                      清空查询
                    </Button>
                  </Form.Item>

                  <Form.Item>
                    <Button className="btn">
                      <CSVLink
                        className="delete"
                        data={data}
                        filename="导出表.csv"
                      >
                        导出结果
                      </CSVLink>
                    </Button>
                  </Form.Item>
                </Form>

                {/* <Table columns={columns} dataSource={data} /> */}
                <Table
                  columns={columns}
                  bordered={true}
                  pagination={{ defaultPageSize: 5 }}
                  dataSource={data}
                />
              </>
            ),
          },
          {
            label: `添加文章`,
            key: "2",
            children: (
              <>
                <div className="addBox">
                  <Form
                    form={addText}
                    className="boxBig"
                    initialValues={{ remember: true }}
                    name="customized_form_controls"
                    autoComplete="off"
                    layout="inline"
                    onFinish={onAdd}
                  >
                    <Form.Item label="分类" name="atype">
                      <Select style={{ width: "166px" }}>
                        <Select.Option value="公告类">公告类</Select.Option>
                        <Select.Option value="知识类">知识类</Select.Option>
                        <Select.Option value="新闻类">新闻类</Select.Option>
                      </Select>
                    </Form.Item>

                    <Form.Item name="atitle" label="标题">
                      <Input
                        style={{
                          width: "619px",
                          marginTop: "5px",
                          marginBottom: "5px",
                        }}
                      />
                    </Form.Item>

                    <Form.Item label="内容" name="acontent">
                      <ReactQuill
                        className="publish-quill"
                        theme="snow"
                        placeholder="请输入文章内容"
                      />
                    </Form.Item>

                    <Form.Item>
                      <Button
                        type="primary"
                        htmlType="submit"
                        className="search"
                        style={{
                          width: "120px",
                          height: "40px",
                          backgroundColor: "#3c48ee",
                          color: "#fff",
                          marginTop: "50px",
                          marginLeft: "42px",
                        }}
                        onClick={onAdd}
                      >
                        保存
                      </Button>
                    </Form.Item>
                  </Form>
                </div>
              </>
            ),
          },
        ]}
      />

      {/* 编辑框 */}
      <Modal
        title="编辑"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={"确认"}
        cancelText={"取消"}
      >
        <Form
          form={editForm}
          name="basic"
          initialValues={{ remember: true }}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
        >
          <Form.Item label="标题" name="atitle">
            <Input />
          </Form.Item>

          <Form.Item label="分类" name="atype">
            <Select>
              <Select.Option value="公告类">公告类</Select.Option>
              <Select.Option value="知识类">知识类</Select.Option>
              <Select.Option value="新闻类">新闻类</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item label="内容" name="acontent">
            <ReactQuill className="aaa" theme="snow" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
export default PolicyArticles;
